#include "ControlLayer.h"

#include "PeaShooter.h"

bool ControlLayer::init(){

	bool bRet = false;

	 do 
	 {
		 CC_BREAK_IF(! CCLayer::init());
		 m_state = kSpriteBrickUngrabbed;
		 dragSprite = (CCSprite*)PeaShooter::create();
		 dragSprite->setAnchorPoint(RectLayout::TopLeft());
		 dragSprite->setVisible(false);
		 this->addChild(dragSprite);
		bRet = true;

	 } while (0);
	 
	 return bRet;
}

void ControlLayer::onEnter()
{
	CCNode* pSceneLayer = this->getParent()->getChildByTag(kSceneLayer);
	SpriteBrick* psb = (SpriteBrick*)pSceneLayer->getChildByTag(kPeaShooterSpriteBrick);
	psb->AddTouchEventBeginHandle(this);
	psb->AddTouchEventMoveHandle(this);
	psb->AddTouchEventCompleteHandle(this);	

	CCLayer::onEnter();
}

void ControlLayer::touchBeginHandler( CCEvent* e)
{
	if(!GameSetting::isGameStart) return;
	if(m_state != kSpriteBrickUngrabbed) return;
	m_state = kSpriteBrickGrabbed;

	CCNode* pSceneLayer = this->getParent()->getChildByTag(kSceneLayer);
	SpriteBrick* psb = (SpriteBrick*)pSceneLayer->getChildByTag(kPeaShooterSpriteBrick);	
	
	dragSprite->setVisible(true);
	dragSprite->setPosition(psb->getPosition());

}

void ControlLayer::touchMoveHandler( CCPoint touchPoint, CCEvent* e)
{
	if(m_state == kSpriteBrickGrabbed){
		CCNode* pSceneLayer = this->getParent()->getChildByTag(kSceneLayer);
		SpriteBrick* psb = (SpriteBrick*)pSceneLayer->getChildByTag(kPeaShooterSpriteBrick);
		dragSprite->setAnchorPoint(RectLayout::Center());
		dragSprite->setPosition(touchPoint);

	}
}

void ControlLayer::touchCompleteHandler(CCEvent* e)
{
	if(m_state != kSpriteBrickGrabbed) return;
	m_state = kSpriteBrickUngrabbed;
	dragSprite->setAnchorPoint(RectLayout::TopLeft());
	dragSprite->setVisible(false);
}